package org.finesys.common.security.authentication.gitee;

import org.finesys.common.constants.SecurityConstants;
import org.finesys.common.security.authentication.base.OAuth2ResourceOwnerBaseAuthenticationConverter;
import org.finesys.common.security.client.core.endpoint.OAuth2GiteeParameterNames;
import org.finesys.common.security.core.util.OAuth2EndpointUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * gitee 认证转换器
 */
public class OAuth2GiteeAuthenticationConverter extends OAuth2ResourceOwnerBaseAuthenticationConverter<OAuth2GiteeAuthenticationToken> {

    public static final AuthorizationGrantType GITEE = new AuthorizationGrantType(SecurityConstants.GITEE);

    @Override
    public void checkParams(HttpServletRequest request) {
        MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request);
        //检验必须参数：code和AppId
        OAuth2EndpointUtils.checkMustParameters(parameters, OAuth2ParameterNames.CODE, OAuth2GiteeParameterNames.APPID);
    }

    @Override
    public OAuth2GiteeAuthenticationToken bulidToken(Authentication authentication, Set<String> requestedScopes, Map<String, Object> additionalParameters) {
        //获取传递的参数信息
        String code = (String) additionalParameters.get(OAuth2ParameterNames.CODE);
        String state = (String) additionalParameters.get(OAuth2ParameterNames.STATE);
        String scope = (String) additionalParameters.get(OAuth2ParameterNames.SCOPE);
        String appId = (String) additionalParameters.get(OAuth2GiteeParameterNames.APPID);
        String binding = (String) additionalParameters.get(OAuth2GiteeParameterNames.BINDING);
        return new OAuth2GiteeAuthenticationToken(GITEE, authentication, requestedScopes, additionalParameters, appId, code, scope, state, binding);
    }

    /**
     * 是否支持
     */
    public boolean support(String grantType) {
        return GITEE.getValue().equals(grantType);
    }
}
